package com.woniuxy.ams.exception.handle;

import com.woniuxy.ams.entity.ResultEntity;
import com.woniuxy.ams.exception.UserNotExistException;
import com.woniuxy.ams.exception.UserNotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author fyxw
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandle {
    /**
     * 捕捉参数校验异常，封装到json中，返回给用户
     * @param e 捕捉到的参数校验异常
     * @return 封装json对象
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultEntity<?> validExceptionHandle(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        allErrors.forEach(error -> sb.append(error.getDefaultMessage()).append(";"));
        log.debug(sb.toString());
        return new ResultEntity<>(400, sb.toString(), null);

    }
    @ExceptionHandler(UnauthorizedException.class)
    public ResultEntity<?> unauthorizedException(UnauthorizedException e) {
        log.warn("异常原因: "+e.getMessage());
        return new ResultEntity<>(403, "权限不允许;拒绝访问");
    }

    /**
     * 默认的异常捕获机制
     * @param e 捕获的异常
     * @return 服务器维护消息
     */
    @ExceptionHandler(Exception.class)
    public ResultEntity<?> defaultException(Exception e) {
        log.warn("异常原因: "+e.getMessage());
        return new ResultEntity<>(500, "服务器维护中", null);
    }

    @ExceptionHandler(UserNotExistException.class)
    public ResultEntity<?> userNotExistException(UserNotExistException e) {
        log.warn(e.getMessage());
        return new ResultEntity<>(403, e.getMessage());
    }

    @ExceptionHandler(UserNotLoginException.class)
    public ResultEntity<?> userNotLoginException(UserNotLoginException e) {
        log.warn(e.getMessage());
        return new ResultEntity<>(401, e.getMessage());
    }
}
